package com.line.myprojectservice.chatserver.handler;

import cn.hutool.json.JSONObject;
import com.line.myprojectservice.chatserver.constant.Constants;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import static com.line.myprojectservice.chatserver.service.PublicService.allConnectedMap;
import static com.line.myprojectservice.chatserver.service.PublicService.sendMessage;

//线程问题，我该关心什么



/**
 * @author Line
 */
@Slf4j
@ChannelHandler.Sharable
public class GuiderHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    JSONObject jsonObject = new JSONObject();
    String message = "";

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {

        if (evt.equals(Constants.FIRST_SOCKET)) {
            jsonObject.set("start", "您好");
            sendMessage(jsonObject.toString(), ctx.channel());
        }
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {

        message = msg.text();

        if (c("皮肤") || c("表面") || c("毛孔")) {
            message = "皮肤科";
        } else if (c("嘴巴") || c("口腔") || c("嘴")) {
            message = "口腔科";
        } else if (c("耳朵") || c("鼻子") || c("喉咙")) {
            message = "耳鼻喉科";
        } else if (c("心脏") || c("胸口") || c("心")) {
            message = "心血管内科";
        } else if (c("脑子") || c("头") || c("精神")) {
            message = "精神科";
        } else if (c("保健") || c("养生") || c("健康")) {
            message = "营养保健科";
        } else if (c("牙齿") || c("牙") || c("牙龈")) {
            message = "牙科";
        } else if (c("孩子") || c("小孩") || c("孩")) {
            message = "儿科";
        } else {
            message = "对不起";
        }

        jsonObject.clear();

        jsonObject.set("mes", message);

        sendMessage(jsonObject.toString(), ctx.channel());

    }

    boolean c(String key) {
        return message.contains(key);
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {

        //发生异常时候调用关闭错误连接
        channelInactive(ctx);

        log.error("发生错误");
        cause.printStackTrace();
    }


    /**
     * channelActive 只有当 Channel 变为活动状态,就TCP而言,这意味着连接建立时,
     * 如果添加 ChannelHandler 连接通道后,它将不再看到活动事件。
     * 所以用这个事件处理
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {

        log.info("挂载导游处理器到线上");

    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) {

        log.info("有一连接关闭，Id={} , 当前在线人数为：{}", ctx.channel().id(), allConnectedMap.size());

    }

}

